<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="活动名称" prop="promotionName">
        <el-input v-model="queryParams.promotionName" placeholder="请输入活动名称" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="活动状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.goods_promotion_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="dateRanges" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['store:promotion:fullDiscount_zone:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate" v-hasPermi="['store:promotion:fullDiscount_zone:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete" v-hasPermi="['store:promotion:fullDiscount_zone:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['store:promotion:fullDiscount_zone:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['store:promotion:fullDiscount_zone:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动编号" prop="id" width="200" align="center" />
      <el-table-column label="活动名称" prop="promotionName" :show-overflow-tooltip="true" width="200"
        align="center" />
      <el-table-column label="背景图" prop="detailAppImage" :show-overflow-tooltip="true" width="70"
        align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px" :src="scope.row.detailAppImage"
            :preview-src-list="scope.row.detailAppImage">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="活动描述" prop="description" width="200" align="center" />
      <el-table-column label="开始时间" prop="startTime" align="center" width="200" />
      <el-table-column label="结束时间" prop="endTime" align="center" width="200" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" prop="promotionStatus" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.promotion_promotion_status"
            :value="scope.row.promotionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['store:promotion:fullDiscount_zone:edit']">修改</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['store:promotion:promotion:goods:import', 'store:promotion:promotion:goods:page']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-button type="info" plain icon="el-icon-upload2" size="mini"
                @click="Uploadproduct(scope.row)" v-hasPermi="['store:promotion:promotion:goods:import']">
                上传商品</el-button>
              <el-button type="info" plain icon="el-icon-magic-stick" size="mini"
                @click="commodityDetails(scope.row)"
                v-hasPermi="['store:promotion:promotion:goods:page']">
                商品详情</el-button>
              <el-button type="info" plain icon="el-icon-magic-stick" size="mini"
                @click="promotionRule(scope.row)" v-hasPermi="['store:promotion:fullDiscount_zone:rule:list']">
                促销规则</el-button>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="text" icon="el-icon-tableware" size="mini"
            @click="urgentClose(scope.row)" v-hasPermi="['store:promotion:fullDiscount_zone:cancel']">
            紧急关闭</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改专区满折对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="promotionName" :show-overflow-tooltip="true">
          <el-input v-model="form.promotionName" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" class="start">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true"
            v-if="updateTimeParagraphStatus === '新增活动'"></el-date-picker>
          <span v-if="updateTimeParagraphStatus === '修改活动'"> {{form.startTime}} </span>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="选择日期时间" :show-overflow-tooltip="true"
            v-if="updateTimeParagraphStatus === '新增活动'"></el-date-picker>
          <span v-if="updateTimeParagraphStatus === '修改活动'">{{form.endTime}}</span>
        </el-form-item>
        <el-form-item label="背景图" prop="detailAppImage" label-width="92px">
          <div v-if="updateTimeParagraphStatus === '修改活动'">
            <input type="file" @change="requiredChange" v-show="!detailAppImageStatus">
            <img class="detailAppImage" :src="form.detailAppImage" v-show="detailAppImageStatus">
            <span @click="deletePicture" v-show="detailAppImageStatus">删除</span>
          </div>
          <div v-if="updateTimeParagraphStatus === '新增活动'">
            <input id="files" type="file" @change="requiredChange" v-show="!detailAppImageStatus">
            <img class="detailAppImage" :src="form.detailAppImage" v-show="detailAppImageStatus">
            <span @click="deletePicture" v-show="detailAppImageStatus">删除</span>
          </div>
          <!-- <el-upload action="#" list-type="picture-card" :auto-upload="false"
            :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg"
            :show-overflow-tooltip="true">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete"
                  @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" :show-overflow-tooltip="true" />
          </el-dialog> -->
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠
          </el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">
            全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="deptOptions" show-checkbox default-expand-all
            ref="dept" node-key="id" :check-strictly="!form.deptCheckStrictly" empty-text="加载中，请稍候"
            :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 专区满折导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action=" r+'/store/promotion/promotion/FULL_DISCOUNT_ZONE/' + id + '/importData' + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品详情 -->
    <el-dialog title="商品详情" :visible.sync="open4" width="1000px">
      商品编码: <el-input v-model="FULLDISCOUNTLISTFORM.identifier" style="width:200px" clearable>
      </el-input>
      商品名称: <el-input v-model="FULLDISCOUNTLISTFORM.goodsName" style="width:200px" clearable>
      </el-input>
      <el-button type="danger" @click="goodsList" style="margin:0 0 20px 20px">搜索</el-button>

      <el-button type="primary" plain icon="el-icon-download" size="mini"
        style="margin:0 0 20px 20px" @click="handlePromotionGoodsExport"
        v-hasPermi="['store:promotion:promotion:goods:export']">导出商品
      </el-button>
      <el-table :data="FULLDISCOUNTLIST">
        <el-table-column label="排序" prop="orderNum" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.orderNum"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品编码" prop="identifier" align="center"> </el-table-column>
        <el-table-column label="商品名称" prop="goodsName" align="center" width="300px">
        </el-table-column>
        <el-table-column label="规格" prop="simpleSpecs" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="商品原价" prop="originalPrice" align="center"></el-table-column>
        <el-table-column label="已购数量" prop="num" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" @click="modifySeckillCommodity(scope.row)" v-hasPermi="['store:promotion:promotion:goods:edit']">修改</el-button>
            <el-button size="mini" @click="delSeckillCommodity(scope.row)" v-hasPermi="['store:promotion:promotion:goods:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="parseInt(FULLDISCOUNTLISTFORM.total) >0"
        :total="parseInt(FULLDISCOUNTLISTFORM.total)" :page.sync="FULLDISCOUNTLISTFORM.pageNum"
        :limit.sync="FULLDISCOUNTLISTFORM.pageSize" @pagination="goodsList" />
    </el-dialog>

    <!-- 确认框 -->
    <el-dialog title="提示" :visible.sync="open3" width="400px">
      <p> 确认 {{updateTimeParagraphStatus}} 吗？ </p>
      <el-button @click="open3 = false">取消</el-button>
      <el-button @click="determineDelete">确定</el-button>
    </el-dialog>

    <!-- 活动 的 规则 -->
    <el-dialog title="促销规则" :visible.sync="open5" width="600px">
      <el-button @click="addRule" v-hasPermi="['store:promotion:fullDiscount_zone:rule:add']">新建----></el-button>
      <span style="margin-right:30px"></span>
      <span>满多少：<el-input v-model="fullMoney" style="width:100px;margin-right:30px">
        </el-input>
      </span>
      <span>打折：<el-input v-model="fullRate" style="width:100px;margin-bottom:20px">
        </el-input>
      </span>
      <el-table :data="RULE">
        <el-table-column label="序号" type="index" align="center"> </el-table-column>
        <el-table-column label="满多少" prop="fullMoney" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.fullMoney" style="width:100px;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="打折" prop="fullRate" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.fullRate" style="width:100px;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250px">
          <template slot-scope="scope">
            <el-button size="mini" @click="delRule(scope.row)" v-hasPermi="['store:promotion:fullDiscount_zone:rule:remove']">删除</el-button>
            <el-button size="mini" @click="updRule(scope.row)" v-hasPermi="['store:promotion:fullDiscount_zone:rule:edit']">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  listFullDiscount, getRole, delRole, addFullDiscount, updateFullDiscount, dataScope,
  getGoodsActivityRuleList, addGoodsActivityRule, updGoodsActivityRule, delGoodsActivityRule, closeActivity
} from "@/api/promotion/fullDiscountZone"
import { getPromotionGoodsList, updatePromotionGoods, delPromotionGoods } from "@/api/promotion/promotions.js"
import { uploadPicture } from "@/api/promotion/seckillZone"
import axios from "axios"
import { getToken } from "@/utils/auth";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu"
import { treeselect as deptTreeselect, roleDeptTreeselect } from "@/api/system/dept"

export default {
  name: "FullDiscountZone",
  dicts: ["goods_promotion_status", "promotion_promotion_status"],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      dateRanges: [],
      id: "",
      r: process.env.VUE_APP_BASE_API,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() }
        // 上传的地址
        // url:
        //   process.env.VUE_APP_BASE_API +
        //   "/store/promotion/promotion/BARGAIN/" +
        //   this.id +
        //   "/importData"
      },
      // 数据范围选项
      dataScopeOptions: [
        { value: "1", label: "全部数据权限" },
        { value: "2", label: "自定数据权限" },
        { value: "3", label: "本部门数据权限" },
        { value: "4", label: "本部门及以下数据权限" },
        { value: "5", label: "仅本人数据权限" }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: { pageNum: 1, pageSize: 10, roleName: undefined, roleKey: undefined, status: undefined },
      // 表单参数
      form: {},
      defaultProps: { children: "children", label: "label" },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      imageFileList: undefined,
      headers: { Authorization: "Bearer " + getToken(), "Content-Type": "multipart/form-data" },
      // 表单校验
      rules: {
        promotionName: [{ required: true, message: "活动名称不能为空", trigger: "blur" }],
        startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
        endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
        detailAppImage: [{ required: true, message: "背景图不能为空", trigger: "blur" }]
      },

      // //
      // FULL_DISCOUNT
      FULLDISCOUNTLISTFORM: {
        total: '',
        pageNum: 1,
        pageSize: 10,
        identifier: '',
        goodsName: '',
      },
      FULLDISCOUNTLIST: [],
      open3: false,
      open4: false,
      open5: false,
      updateTimeParagraphStatus: '',
      id: '',
      ROWS: {},
      RULE: [],
      fullMoney: '',
      fullRate: '',
      row: {},
      detailAppImageStatus: false,
    }
  },
  created () {
    this.getList();
  },
  methods: {

    handlePromotionGoodsExport () {
      this.download('store/promotion/promotion/' + this.row.id + '/export?promotionType=FULL_DISCOUNT_ZONE&identifier=' + this.FULLDISCOUNTLISTFORM.identifier + '&goodsName=' + this.FULLDISCOUNTLISTFORM.goodsName, {
        ...this.addDateRangeWithMap(this.addDateRangeWithMap(this.queryParams, this.dateRange, "CreateTime"), this.payDateRange, "PaymentTime")
      }, `专区满折商品列表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`)
    },

    // 紧急关闭 活动
    urgentClose (row) {
      this.row = row
      this.updateTimeParagraphStatus = '关闭活动'
      this.open3 = true
    },
    // 商品详情
    commodityDetails (row) {
      this.row = row
      this.open4 = true
      this.goodsList()
    },
    // 促销 按钮
    promotionRule (row) {
      this.ROWS = row
      this.open5 = true
      // 查看 促销 规则
      this.ruleList()
    },
    // 专区 促销 规则
    ruleList () {
      getGoodsActivityRuleList(this.ROWS.id).then(res => {
        if (res.code === 200) {
          this.RULE = res.rows
        }
      })
    },
    // 删除商品
    delSeckillCommodity (row) {
      this.updateTimeParagraphStatus = '删除商品'
      this.ROWS = row
      this.open3 = true
    },
    // 修改商品
    modifySeckillCommodity (row) {
      this.updateTimeParagraphStatus = '修改商品'
      this.ROWS = row
      this.open3 = true
    },
    // 获取数据列表
    // 获取数据
    goodsList () {
      getPromotionGoodsList(this.row.id, {
        promotionType: 'FULL_DISCOUNT_ZONE',
        ...(this.FULLDISCOUNTLISTFORM)
      }).then(res => {
        if (res.code === 200) {
          this.FULLDISCOUNTLIST = res.rows
          this.FULLDISCOUNTLISTFORM.total = res.total
        }
      })
    },
    // 确定框 确定
    determineDelete () {
      // 关闭 活动
      if (this.updateTimeParagraphStatus === '关闭活动') {
        if (this.row.promotionStatus === 'NEW' || this.row.promotionStatus === 'START') {
          closeActivity(this.row.id, { promotionStatus: 'CLOSE' }).then(res => {
            if (res.code === 200) {
              this.$modal.msgSuccess("操作成功")
              this.open3 = false
              this.getList()
            }
          })
        }
      }
      if (this.updateTimeParagraphStatus === '删除商品') {
        delPromotionGoods('FULL_DISCOUNT_ZONE', this.row.id, this.ROWS.id).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("操作成功")
            this.open3 = false
            this.goodsList()
          }
        })
      }
      // 修改 商品
      if (this.updateTimeParagraphStatus === '修改商品') {
        updatePromotionGoods('FULL_DISCOUNT_ZONE', this.row.id, this.ROWS.id, { orderNum: this.ROWS.orderNum }).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("操作成功")
            this.open3 = false
            this.goodsList()
          }
        })
      }
      if (this.updateTimeParagraphStatus === '删除规则') {
        delGoodsActivityRule(this.ROWS.id, this.ROWRule.id).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("操作成功")
            this.open3 = false
            this.ruleList()
          }
        })
      }
      if (this.updateTimeParagraphStatus === '修改规则') {
        updGoodsActivityRule(this.ROWS.id, this.ROWRule.id, { fullMoney: this.ROWRule.fullMoney, fullRate: this.ROWRule.fullRate }).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("操作成功")
            this.open3 = false
            this.ruleList()
          }
        })
      }
    },
    // 增 加 规则
    addRule () {
      addGoodsActivityRule(this.ROWS.id, { fullMoney: this.fullMoney, fullRate: this.fullRate }).then(res => {
        if (res.code === 200) {
          this.fullMoney = ''
          this.fullRate = ''
          this.ruleList()
        }
      })
    },
    delRule (row) {
      this.ROWRule = row
      this.updateTimeParagraphStatus = "删除规则"
      this.open3 = true
    },
    updRule (row) {
      this.ROWRule = row
      this.updateTimeParagraphStatus = "修改规则"
      this.open3 = true
    },


    // 删除图片
    deletePicture () {
      if (this.updateTimeParagraphStatus === '新增活动') {
        document.getElementById('files').value = ''
      }
      this.form.detailAppImage = ''
      this.detailAppImageStatus = false
    },
    // 上传图片
    requiredChange (e) {
      let formdata = new FormData()
      formdata.append("file", e.target.files[0])
      uploadPicture(formdata).then(res => {
        if (res.code === 200) {
          this.form.detailAppImage = res.data.url
          this.detailAppImageStatus = true
        }
      })
    },


    /** 查询角色列表 */
    getList () {
      this.loading = true;
      listFullDiscount(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect () {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 查询部门树结构 */
    getDeptTreeselect () {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },

    // 所有部门节点数据
    getDeptAllCheckedKeys () {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect (roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect (roleId) {
      return roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },

    // 取消按钮
    cancel () {
      this.open = false;
      if (this.updateTimeParagraphStatus === '新增活动') {
        this.form.detailAppImage = ''
        document.getElementById('files').value = ''
        this.detailAppImageStatus = false
        this.form = {}
      }
    },
    // 取消按钮（数据权限）
    cancelDataScope () {
      this.openDataScope = false;
    },
    // 表单重置
    reset () {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand (value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.updateTimeParagraphStatus = '新增活动'
      this.detailAppImageStatus = false
      this.form = {}
      this.open = true;
      this.title = "添加专区满折";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.updateTimeParagraphStatus = '修改活动'
      this.form = row;
      this.form.detailAppImage = row.detailAppImage
      this.detailAppImageStatus = true
      this.open = true;
      this.title = "修改专区满折";
    },
    // 上传商品
    Uploadproduct (row) {
      this.upload.title = "专区满折商品导入";
      this.upload.open = true;
      this.id = row.id;
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange (value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配数据权限操作 */
    handleDataScope (row) {
      this.reset();
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.updateTimeParagraphStatus === '修改活动') {
        updateFullDiscount(this.form).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          }
        })
      } else {
        addFullDiscount(this.form).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          }
        })
      }
    },
    // submitForm: function () {
    //   if (this.imageFileList) {
    //     const loading = this.$loading({
    //       lock: true,
    //       text: "上传中...",
    //       spinner: "el-icon-loading",
    //       background: "rgba(0, 0, 0, 0.7)"
    //     });
    //     let formData = new FormData();
    //     formData.append("file", this.imageFileList[0].raw);
    //     axios
    //       .post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
    //         headers: this.headers
    //       })
    //       .then(res => {
    //         if (res.status == 200) {
    //           let data = res.data;
    //           if (data.code == 200) {
    //             this.$modal.msgSuccess("上传成功");
    //             this.form.detailAppImage = data.data.url;
    //             if (this.form.id != undefined) {
    //               updateFullDiscount(this.form).then(response => {
    //                 console.log(this.form);
    //                 this.$modal.msgSuccess("修改成功");
    //                 this.open = false;
    //                 this.getList();
    //               });
    //             } else {
    //               addFullDiscount(this.form).then(response => {
    //                 this.$modal.msgSuccess("新增成功");
    //                 this.open = false;
    //                 this.getList();
    //               });
    //             }
    //           } else {
    //             this.$message.error("上传文件失败" + res.data.msg);
    //           }
    //         }
    //       })
    //       .finally(res => {
    //         loading.close();
    //       });
    //     return;
    //   }
    // },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const roleIds = row.roleId || this.ids;
      this.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return delRole(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download(
        "store/promotion/promotion/goods/importTemplate",
        {},
        `导入专区满折商品模板_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`
      );
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
      console.log("event", event);
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      console.log("response", response);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "专区满折商品导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "store/promotion/promotion/goods/importTemplate",
        {
          ...this.queryParams
        },
        `导出专区满折商品_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`
      );
    },
    // 删除图片
    handleRemove (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.removeChild(ul.children[0]);
      ul.nextSibling.style.display = "block";
      console.log(file, fileList);
    },
    // 预览图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.raw.url;
      this.dialogVisible = true;
    },
    //   上传图片
    changeImg (file, fileList) {
      const ul = document.querySelector(".el-upload-list--picture-card");
      ul.nextSibling.style.display = "none";
      console.log(file, fileList);
      this.imageFileList = fileList;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  top: 20px;
  img {
    width: 200px;
    height: 200px;
  }
}
</style>
